package com.shike.palmrejection;

import android.app.TimePickerDialog;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView mStartTime;
    private TextView mEndTime;

    private EditText mDayPoint;
    private EditText mNightPoint;
//    private EditText mMillisecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 服务保活
        startService(new Intent(this, SaveService.class));

        mStartTime = findViewById(R.id.start_time);
        mEndTime = findViewById(R.id.end_time);
        mStartTime.setOnClickListener(this);
        mEndTime.setOnClickListener(this);

        mDayPoint = findViewById(R.id.day_point);
        mNightPoint = findViewById(R.id.night_point);
//        mMillisecond = findViewById(R.id.millisecond);

        findViewById(R.id.save_set).setOnClickListener(this);

        // 判断是否首次进入，如果是初始化内容
        if (!SharepreferenceUtils.getBoolean(MainActivity.this, Config.IS_FIRST, false)) {

            findViewById(R.id.show).setVisibility(View.VISIBLE);

            // 记录第一次
            SharepreferenceUtils.saveBoolean(MainActivity.this, Config.IS_FIRST, true);

            SharepreferenceUtils.saveString(this, Config.S_HM, "8:00");
            SharepreferenceUtils.saveString(this, Config.E_HM, "18:00");
            SharepreferenceUtils.saveString(this, Config.DAY_POINT, "50");
            SharepreferenceUtils.saveString(this, Config.NIGHT_POINT, "10");
            SharepreferenceUtils.saveString(this, Config.MILLISECOND, "1000");
        }

        // 写入记录的时间段
        mStartTime.setText(SharepreferenceUtils.getString(MainActivity.this, Config.S_HM, ""));
        mEndTime.setText(SharepreferenceUtils.getString(MainActivity.this, Config.E_HM, ""));

        mDayPoint.setText(SharepreferenceUtils.getString(this, Config.DAY_POINT, "50"));
        mNightPoint.setText(SharepreferenceUtils.getString(this, Config.NIGHT_POINT, "10"));
//        mMillisecond.setText(SharepreferenceUtils.getString(this, Config.MILLISECOND, "1000"));

    }

    public void onClickSetPar(View view) {
        findViewById(R.id.show).setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        if (v == mStartTime) {
            new TimePickerDialog(this, R.style.Theme_AudioDialog, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                    SharepreferenceUtils.saveString(MainActivity.this, Config.S_HM, hourOfDay + ":" + (minute > 9 ? minute : ("0" + minute)));

                    mStartTime.setText(hourOfDay + ":" + (minute > 9 ? minute : ("0" + minute)));
                }
            }, 8, 0, true).show();

        } else if (v == mEndTime) {
            new TimePickerDialog(this, R.style.Theme_AudioDialog, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                    if (SharepreferenceUtils.getString(MainActivity.this, Config.S_HM, null) == null) {
                        Toast.makeText(MainActivity.this, "请先选择开始时间！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    int sHm = Integer.parseInt(SharepreferenceUtils.getString(MainActivity.this, Config.S_HM, "0").replace(":", ""));
                    int eHm = Integer.parseInt(hourOfDay + "" + (minute > 9 ? minute : ("0" + minute)));
                    if (sHm >= eHm) {
                        Toast.makeText(MainActivity.this, "能不能认真点！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    SharepreferenceUtils.saveString(MainActivity.this, Config.E_HM, hourOfDay + ":" + (minute > 9 ? minute : ("0" + minute)));

                    mEndTime.setText(hourOfDay + ":" + (minute > 9 ? minute : ("0" + minute)));
                }
            }, 18, 0, true).show();
        } else if (v.getId() == R.id.save_set) {
//            screenOff();
            findViewById(R.id.show).setVisibility(View.GONE);
            // 保存
            SharepreferenceUtils.saveString(this, Config.DAY_POINT, mDayPoint.getText().toString());
            SharepreferenceUtils.saveString(this, Config.NIGHT_POINT, mNightPoint.getText().toString());
//            SharepreferenceUtils.saveString(this, Config.MILLISECOND, mMillisecond.getText().toString());
        }
    }

    public void startZiQi(View view) {
        Intent intent2 = new Intent();
        intent2.setAction("miui.intent.action.OP_AUTO_START");
        intent2.addCategory("android.intent.category.DEFAULT");
        startActivity(intent2);
    }

    public void startQuanXian(View view) {
        try { // MIUI 8
            Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", getPackageName());
            startActivity(localIntent);
        } catch (Exception e) {
            try { // MIUI 5/6/7
                Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                localIntent.putExtra("extra_pkgname", getPackageName());
                startActivity(localIntent);
            } catch (Exception e1) { // 否则跳转到应用详情
                startActivity(getAppDetailSettingIntent());
            }
        }
    }

    /**
     * 获取应用详情页面intent
     *
     * @return
     */
    private Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        return localIntent;
    }

    public void onClickNormal(View view) {
        findViewById(R.id.show).setVisibility(View.GONE);
    }



    private void screenOff(){
        DevicePolicyManager policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName adminReceiver = new ComponentName(this, ScreenOffAdminReceiver.class);
        boolean admin = policyManager.isAdminActive(adminReceiver);
        if (admin) {
            policyManager.lockNow();
        } else {
            Toast.makeText(this,"没有设备管理权限",
                    Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Receiver class which shows notifications when the Device Administrator status
     * of the application changes.
     */
    public static class ScreenOffAdminReceiver extends DeviceAdminReceiver {
        private void showToast(Context context, String msg) {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEnabled(Context context, Intent intent) {
            showToast(context,
                    "设备管理器使能");
        }

        @Override
        public void onDisabled(Context context, Intent intent) {
            showToast(context,
                    "设备管理器没有使能");
        }

    }
}
